<?php
/**
 * 会员模型.
 * User: ysongyang
 * Date: 2017/7/25
 * Time: 17:17
 */

namespace app\model;

use think\Model;
use think\Request;
use think\Cookie;

class User extends Model
{

    protected $autoWriteTimestamp = 'datetime';

    /**
     * @author: ysongyang <ysongyang@qq.com>
     * 自定义获取用户属性的方法
     * @param int $id
     * @param string $field
     * @return mixed
     */
    public function getUserField($id, $field)
    {
        $data = $this->field($field)->where('id', $id)->find();
        return $data[$field];
    }

    /**
     * 注册
     * @param Request $request
     * @return User|array|false|\PDOStatement|string|Model
     */
    public function register(Request $request)
    {
        if ($request->isPost()) {
            $email = $request->param('email');
            $username = $request->param('username');
            $password = authcode($request->param('pass'), 'ENCODE', '', 0);
            $headimgurl = config('upload_path') . 'default/avatar/' . rand(0, 41) . '.jpg';
            $regdate = date('Y-m-d H:i:s');
            $regip = get_client_ip();
            $cityInfo = GetIpLookup($regip);
            $level = $this->count() == 0 ? 99 : -1;
            $data = ['email' => $email, 'username' => $username, 'password' => $password, 'headimgurl' => $headimgurl, 'country' => $cityInfo['country'], 'province' => $cityInfo['province'], 'city' => $cityInfo['city'], 'regdate' => $regdate, 'regip' => $regip, 'level' => $level, 'lastdate' => $regdate, 'lastip' => get_client_ip()];
            $id = $this->insertGetId($data);
            $user = $this->search(['id' => $id]);
            $expLog = new ExperienceLog();
            $expLog->regUser($id);
            return $user;
        }
        return null;
    }

    /**
     * @param $where
     * @param string $filed
     * @return array|false|\PDOStatement|string|Model
     */
    public function search($where, $filed = "*")
    {
        $user = $this->where($where)->field($filed)->find();
        if (!empty($user)) {
            $user = $user->toArray();
        }
        //echo User::getLastSql();
        return $user;
    }

    /**
     * QQ注册
     * @param $data
     * @return false|int
     */
    public function qqregister($data)
    {
        $id = $this->insertGetId($data);
        $expLog = new ExperienceLog();
        $expLog->regUser($id);
        return $id;
    }

    /**
     * SINA注册
     * @param $data
     * @return false|int
     */
    public function sinaregister($data)
    {
        $id = $this->insertGetId($data);
        $expLog = new ExperienceLog();
        $expLog->regUser($id);
        return $id;
    }


    /**
     * 检测登录方法
     * @param $email
     * @param $password
     * @return bool
     */
    public function login($email, $password)
    {
        $where['email'] = $email;
        $user = $this->search($where);
        if ($user && authcode($user['password'], 'DECODE', '', 0) == $password) {
            unset($user["password"]);
            //Session::set("userinfo", $user);
            return $user;
        }
    }

    //获得用户注册量
    public function user_count()
    {
        return $this->count();
    }

    //更改用户密码
    public function updatepassword($where, $password)
    {
        $user = $this->where($where)->update(['password' => authcode($password, 'ENCODE', '', 0)]);
        if ($user) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 记录访客信息
     * 如果访问某个会员 已经存储了这个访客记录 则进行更新
     * 避免累积添加数据造成数据冗余
     * @param $uid      访问者UID
     * @param @fuid     访问谁UID
     */
    public function insertGuest($uid, $fuid)
    {
        if ($uid != $fuid) {
            $where = ['uid' => $uid, 'fuid' => $fuid];
            //先查询访问这个人 是否有访客信息
            $check = db('guest')->where($where)->select();
            if ($check) {
                db('guest')->where($where)->update(['guest_time' => date('Y-m-d H:i:s')]);
            } else {
                $data = array(
                    'uid' => $uid,
                    'fuid' => $fuid,
                    'guest_time' => date('Y-m-d H:i:s')
                );
                db('guest')->insert($data);
            }
        }
    }

    /**
     * 获得最近访客
     */
    public function getGuest($uid)
    {
        $data = db('guest')->where(['fuid' => $uid])->order('guest_time desc')->select();
        foreach ($data as $key => $val) {
            $username = $this->search(['id' => $val['uid']], 'username');
            $avatar = $this->search(['id' => $val['uid']], 'headimgurl');
            $data[$key]['username'] = $username['username'];
            $data[$key]['avatar'] = $avatar['headimgurl'];
            $data[$key]['guest_time'] = wordTime($val['guest_time']);
        }
        return $data;
    }


    /**
     * 更新用户信息
     * @param $where
     * @param $data
     * @return bool
     */
    public function saveUser($where, $data)
    {
        $user = $this->where($where)->update($data);
        if ($user) {
            return true;
        } else {
            return false;
        }
    }

    //当用户勾选"记住我"
    public function saveRemember($uid, $identifier, $token, $timeout)
    {
        $data['identifier'] = $identifier;
        $data['token'] = $token;
        $data['timeout'] = time() + $timeout;
        $where = "id = " . $uid;
        $res = $this->where($where)->update($data);
        return $res;
    }

    //验证用户是否永久登录（记住我）
    public function checkRemember()
    {
        $arr = array();
        $now = time();
        $auth = Cookie::get('loginauth');
        if (!empty($auth)) {
            list($identifier, $token) = explode(':', $auth);
            if (ctype_alnum($identifier) && ctype_alnum($token)) {
                $arr['identifier'] = $identifier;
                $arr['token'] = $token;
            } else {
                return false;
            }
            $info = $this->search($arr);
            if ($info != null) {
                if ($arr['token'] != $info['token']) {
                    return false;
                } else if ($now > $info['timeout']) {
                    return false;
                } else {
                    return $info;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //获取用户列表
    public function getUserList($id)
    {
        $map = array();
        if (!empty($id)) {
            $map['user.id'] = $id;
        }
        $list = $this->alias('user')
            ->field('user.id,user.openid,user.sina_openid,user.email,user.username,user.age,user.mobile,user.gender,user.sign,user.level,user.headimgurl,user.province,user.city,user.area,user.experience,user.regdate,user.lastdate,user.lastip,user.activated,user.lock,level.name as level_name')
            ->where($map)
            ->join('pe_level level', 'level.id=user.level', 'LEFT')
            ->order('user.regdate desc')
            ->select();
        if (empty($id)) {
            foreach ($list as $key => $val) {
                if (!empty($val['openid'])) {
                    $list[$key]['email'] = $list[$key]['email'] . ' <i class="fa fa-qq"></i>';
                }
                if (!empty($val['sina_openid'])) {
                    $list[$key]['email'] = $list[$key]['email'] . ' <i class="fa fa-weibo"></i>';
                }
                $list[$key]['gender'] = $list[$key]['gender'] == 1 ? '男' : '女';
                $list[$key]['lock'] = $list[$key]['lock'] == 1 ? '<span class="text-success">正常</span>' : '<span class="text-danger">锁定</span>';
                $list[$key]['activated'] = $list[$key]['activated'] == 1 ? '<span class="text-success">激活</span>' : '<span class="text-warning">未激活</span>';
            }
        }
        return $list;
    }
}